package com.smartsaas.ugclivii.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.smartsaas.ugclivii.cd.BomTreeHandler;
import com.smartsaas.ugclivii.entity.BomConfig;
import com.smartsaas.ugclivii.ui.UiContext;
import com.smartsaas.ugclivii.utils.FunUtils;
import nxopen.*;
import nxopen.blockstyler.BodyCollector;
import nxopen.blockstyler.Node;
import nxopen.blockstyler.Tree;
import nxopen.layer.LayerManager;
import nxopen.layer.State;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.smartsaas.ugclivii.ui.UiContext.SESSION;

public class JobUtils {
    public static Map<Integer,List<Body>> bodyMap=new HashMap<>();

    public static void loadBody() throws RemoteException, NXException {
        BodyCollection bodies = SESSION.parts().work().bodies();
        TaggedObjectCollection.Iterator iterator = bodies.iterator();
        bodyMap.clear();
        while (iterator.hasNext()){
            Body next = (Body)iterator.next();
            int layer = next.layer();
            bodyMap.computeIfAbsent(layer, k -> new ArrayList<>());
            bodyMap.get(layer).add(next);
        }
    }
    public static void loadLayer() {
        UiContext instance = UiContext.getInstance();
        try
        {
            boolean hiddenNoObjLayer = instance.getLayerHidden().value();
            Tree designTree = instance.getDesignTree();
            Node older = designTree.rootNode();
            if (older!=null){
                designTree.deleteNode(older);
            }
            Node root = designTree.createNode( "All" );
            designTree.insertNode(root, null,null, Tree.NodeInsertOption.LAST);
            root.setState(1);
            root.expand(Node.ExpandOption.EXPAND);
            LayerManager layers = SESSION.parts().work().layers();
            for (int i = 1; i <= 256; i++) {
                List<Body> bodyList = bodyMap.get(i);
                if (bodyList==null&&hiddenNoObjLayer){
                    continue;
                }
                State state = layers.getState(i);
                Node node = designTree.createNode( "" + i);
                designTree.insertNode(node, root,null, Tree.NodeInsertOption.LAST);
                node.setState(1);
                node.setColumnDisplayText(0, "" + i);
                node.setColumnDisplayText(1, state.name());
                node.setColumnDisplayText(3, (bodyList!=null?bodyList.size():0)+"");
            }
        }
        catch(Exception ex)
        {
            instance.debug(ex);
        }
    }
    public static boolean DESIGN_TREE_LOCK=false;
    public static void lockDesignTree() {
        DESIGN_TREE_LOCK=true;
    }
    public static void designTreeInitColumn() throws NXException, RemoteException {
        UiContext instance=UiContext.getInstance();
        Tree designTree = instance.getDesignTree();
        designTree.insertColumn(0,"图层",150);
        designTree.insertColumn(1,"状态",150);
        designTree.insertColumn(2,"属性",150);
        designTree.insertColumn(3,"数量",150);
        designTree.insertColumn(4,"名称",150);
    }
    public static void jobTreeInitColumn() throws NXException, RemoteException {
        UiContext instance=UiContext.getInstance();
        Tree jobTree = instance.getJobTree();
        jobTree.insertColumn(0,"任务名称",250);
        jobTree.insertColumn(1,"状态",150);
        jobTree.insertColumn(2,"用时",150);
    }

    public static void submitJob(String name,String state,long second) throws NXException, RemoteException {
        UiContext instance=UiContext.getInstance();
        Tree jobTree = instance.getJobTree();
        Node node = jobTree.createNode(name);
        jobTree.insertNode(node,null,null, Tree.NodeInsertOption.ALWAYS_FIRST);
        node.setColumnDisplayText(0,name);
        node.setColumnDisplayText(1,state);
        node.setColumnDisplayText(2,String.valueOf(second));
    }
    public static void doJob(String name,Runnable runnable) throws NXException, RemoteException {
        try {
            submitJob(name,"运行中",0);
            long start = System.currentTimeMillis();
            runnable.run();
            long end = System.currentTimeMillis();
            long l = (end - start) / 1000;
            submitJob(name,"完成",l);
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

    public static void mlTreeInitColumn() throws NXException, RemoteException {
        UiContext instance=UiContext.getInstance();
        Tree mlTree = instance.getMlTree();
        mlTree.insertColumn(0,"层",150);
        mlTree.insertColumn(1,"编码",150);
        mlTree.insertColumn(2,"标识符",150);
        mlTree.insertColumn(3,"长",150);
        mlTree.insertColumn(4,"宽",150);
        mlTree.insertColumn(5,"高",150);
        mlTree.insertColumn(6,"坯长",150);
        mlTree.insertColumn(7,"坯宽",150);
        mlTree.insertColumn(8,"坯高",150);
        mlTree.insertColumn(9,"材质",150);
        mlTree.insertColumn(10,"数量",150);
        mlTree.insertColumn(11,"供应商",150);
    }
    private static List<Integer> ML_SELECT_LIST=new ArrayList<Integer>();
    public static void loadMl() {
       try {
           UiContext instance=UiContext.getInstance();
           BodyCollector mlSelection = instance.getMlSelection();
           Tree mlTree = instance.getMlTree();
           boolean isWcsAuto = instance.getWcsAuto().value();
           TaggedObject[] objects = mlSelection.getSelectedObjects();
           String partNumber = instance.getPartNumber().value();
           WCS wcs = SESSION.parts().work().wcs();
           ML_SELECT_LIST.clear();
           if (objects!=null){
               for (TaggedObject object : objects) {
                   if (ML_SELECT_LIST.contains(object.tagValue())){
                       continue;
                   }
                   Body body = (Body) object;
                   ML_SELECT_LIST.add(body.tagValue());
                   List<Body> sameBody = FunUtils.findSameBody(body, objects);
                   if (CollectionUtil.isNotEmpty(sameBody)){
                       for (Body b : sameBody) {
                           ML_SELECT_LIST.add(b.tagValue());
                       }
                   }
                   Node node = mlTree.createNode(body.tag().toString());
                   mlTree.insertNode(node,null,null, Tree.NodeInsertOption.LAST);
                   node.setColumnDisplayText(0,body.layer()+"");
                   node.setColumnDisplayText(1,partNumber+"-"+body.layer()+"-"+body.tag().value);
                   node.setColumnDisplayText(2,body.tag().value+"");
                   node.setColumnDisplayText(10,(sameBody.size()+1)+"");
                   node.setState(1);
                   if (isWcsAuto){
                       double[] distances = FunUtils.getBodyDistances(wcs.coordinateSystem().tag(), body);
                       double rx = instance.getMlrx().value();
                       double ry = instance.getMlry().value();
                       double rz = instance.getMlrz().value();
                       if (distances!=null){
                           node.setColumnDisplayText(3,String.valueOf((int) distances[0]));
                           node.setColumnDisplayText(4,String.valueOf((int)distances[1]));
                           node.setColumnDisplayText(5,String.valueOf((int)distances[2]));
                           node.setColumnDisplayText(6,String.valueOf((int)distances[0]+2*rx));
                           node.setColumnDisplayText(7,String.valueOf((int)distances[1]+2*ry));
                           node.setColumnDisplayText(8,String.valueOf((int)distances[2]+2*rz));
                       }
                   }
               }
           }
       }catch (Exception e){
           UiContext.getInstance().debug(e);
       }
    }

    //初始化电极字段
    public static void eleTreeInitColumn()throws NXException, RemoteException {
        UiContext instance=UiContext.getInstance();
        Tree eleTree = instance.getEleTree();
        eleTree.insertColumn(0,"层",150);
        eleTree.insertColumn(1,"编码",150);
        eleTree.insertColumn(2,"类型",150);
        eleTree.insertColumn(3,"材质",150);
        eleTree.insertColumn(4,"火花间隙",150);
        eleTree.insertColumn(5,"长",150);
        eleTree.insertColumn(6,"宽",150);
        eleTree.insertColumn(7,"高",150);
        eleTree.insertColumn(8,"放量",150);
        eleTree.insertColumn(9,"数量",150);
        eleTree.insertColumn(10,"标识符",150);
        eleTree.insertColumn(11,"石墨费",150);
        eleTree.insertColumn(12,"加工费",150);
        eleTree.insertColumn(13,"供应商",150);
    }
    private static List<Integer> ELE_SELECT_LIST=new ArrayList<Integer>();
    public static void loadEle(){
        try {
            UiContext instance=UiContext.getInstance();
            Tree eleTree = instance.getEleTree();
            ELE_SELECT_LIST.clear();
            boolean isWcsAuto = instance.getWcsAuto().value();
            BodyCollector eleSelection = instance.getEleSelection();
            WCS wcs = SESSION.parts().work().wcs();
            TaggedObject[] objects = eleSelection.getSelectedObjects();
            String partNumber = instance.getPartNumber().value();
            if (objects!=null){
                //需要归类并且统计数量
                for (TaggedObject object : objects) {
                    if (ELE_SELECT_LIST.contains(object.tagValue())){
                        continue;
                    }
                    Body body = (Body) object;
                    ELE_SELECT_LIST.add(body.tagValue());
                    List<Body> sameBody = FunUtils.findSameBody(body, objects);
                    if (CollectionUtil.isNotEmpty(sameBody)){
                        for (Body b : sameBody) {
                            ELE_SELECT_LIST.add(b.tagValue());
                        }
                    }
                    Node node = eleTree.createNode(body.tag().toString());
                    eleTree.insertNode(node,null,null, Tree.NodeInsertOption.LAST);
                    node.setColumnDisplayText(0,body.layer()+"");
                    node.setColumnDisplayText(1,"E"+body.layer()+"-"+body.tag().value);
                    node.setColumnDisplayText(9,(sameBody.size()+1)+"");
                    node.setColumnDisplayText(10,body.tag().value+"");
                    node.setState(1);
                    if (isWcsAuto){
                        double[] distances = FunUtils.getBodyDistances(wcs.coordinateSystem().tag(), body);
                        double rx = instance.getReleaseX().value();
                        double ry = instance.getReleaseY().value();
                        double rz = instance.getReleaseZ().value();
                        if (distances!=null){
                            node.setColumnDisplayText(5,String.valueOf((int) distances[0]+rx*2));
                            node.setColumnDisplayText(6,String.valueOf((int)distances[1])+ry*2);
                            node.setColumnDisplayText(7,String.valueOf((int)distances[2])+rz*2);
                        }
                        node.setColumnDisplayText(8,String.format("长 %.2f 宽%.2f 高 %.2f",rx*2,ry*2,rz*2));
                    }
                }
            }
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

    public static void bomTreeInitColumn() throws NXException, RemoteException {
        UiContext instance=UiContext.getInstance();
        Tree bomTree = instance.getBomTree();
        bomTree.insertColumn(0,"层",150);
        bomTree.insertColumn(1,"编码",150);
        bomTree.insertColumn(2,"一级分类",150);
        bomTree.insertColumn(3,"二级分类",150);
        bomTree.insertColumn(4,"来源",150);
        bomTree.insertColumn(5,"基准坐标",150);
        bomTree.insertColumn(6,"尺寸",200);
        bomTree.insertColumn(7,"数量",150);
        bomTree.insertColumn(8,"标识符",150);
    }

    private static List<Integer> BOM_SELECT_LIST=new ArrayList<Integer>();
    public static void loadBom() {
        try {
            UiContext instance=UiContext.getInstance();
            Tree bomTree = instance.getBomTree();
            BOM_SELECT_LIST.clear();
            BodyCollector bomSelection = instance.getBomSelection();
            boolean isWcsAuto = instance.getWcsAuto().value();
            WCS wcs = SESSION.parts().work().wcs();
            TaggedObject[] objects = bomSelection.getSelectedObjects();
            String partNumber = instance.getPartNumber().value();
            if (objects!=null){
                //需要归类并且统计数量
                for (TaggedObject object : objects) {
                    if (BOM_SELECT_LIST.contains(object.tagValue())){
                        continue;
                    }
                    Body body = (Body) object;
                    BOM_SELECT_LIST.add(body.tagValue());
                    List<Body> sameBody = FunUtils.findSameBody(body, objects);
                    if (CollectionUtil.isNotEmpty(sameBody)){
                        for (Body b : sameBody) {
                            BOM_SELECT_LIST.add(b.tagValue());
                        }
                    }
                    Node node = bomTree.createNode(body.tag().toString());
                    bomTree.insertNode(node,null,null, Tree.NodeInsertOption.LAST);
                    node.setColumnDisplayText(0,body.layer()+"");
                    node.setColumnDisplayText(1,partNumber+"-"+body.layer()+"-BOM"+body.tag().value);
                    node.setColumnDisplayText(7,(sameBody.size()+1)+"");
                    node.setColumnDisplayText(8,body.tag().value+"");
                    node.setState(1);
                    //模料暂不实现
                }
            }
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

    public static void bomCalculatedSize(Tree tree, Node node, Integer csysCode, BomConfig bomConfig){
        try {
            BomTreeHandler.getBodyDistances(tree, node, csysCode, bomConfig);
        }catch (Exception e){
            UiContext.getInstance().debug(e);
        }
    }

}
